package iofile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStream_ {
    public static void main(String[] args) {

    }

    /**
     * @description 读取单个字节，效率较低
     * @throws IOException
     */
    public void readFile_01() throws IOException {
        String filePath = "";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            //创建FileInputStream对象，用于读取对象
            fileInputStream = new FileInputStream(filePath);

            //read()方法返回1个字节的数据，如果已经达到文件的末尾，没有输入可用，返回-1
            while ((readData = fileInputStream.read()) != -1){
                System.out.println((char) readData);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭文件流，释放资源
            fileInputStream.close();
        }
    }

    /**
     * @description 按照字节数组的形式读入，提升效率
     * @throws IOException
     */
    public void readFile_02() throws IOException {
        String filePath = "";
        //创建一个长度为8的字节数组，每次读取8个字节
        byte[] buf = new byte[8];
        int readLength = 0;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);

            //read(byte [])方法将该字节数组长度的数据返回给该数组，正常读取时返回本次读入的字节数（小于等于字节数组的长度）
            //如果已经达到文件的末尾，没有输入可用，返回-1
            while ((readLength = fileInputStream.read(buf)) != -1){
                System.out.println(new String(buf,0,readLength));
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭文件流，释放资源
            fileInputStream.close();
        }
    }
}
